/*
 * Copyright (C) 31/05/2010 Aderbal Nunes <aderbalnunes@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.boxandroid.myrom;

import android.graphics.Canvas;

/**
 * Al life of game
 * 
 * @author aderbal
 * 
 */
public class GameThread extends Thread {
	// constants
	public static final int STATE_READY = 1;
	public static final int STATE_PAUSE = 2;
	public static final int STATE_PLAY = 3;
	public static final int STATE_WINNER = 4;
	public static final int STATE_LOSER = 5;

	// running game?
	public boolean _run = false;
	// surface
	public GameLife _engine;
	// canvas
	public Canvas _canvas;
	// actual state
	public int _state = STATE_READY;

	/**
	 * Constructor
	 * 
	 * @param context
	 */
	public GameThread(GameLife engine) {
		_engine = engine;
	}	
	

	/**
	 * Life of game
	 */
	public void run() {
		while (is_run()) {
			_canvas = null;
			try {
				_canvas = _engine.getHolder().lockCanvas(null);
				synchronized (_engine.getHolder()) {
						_engine.onDraw(_canvas);
				}
			} finally {
				if(_canvas != null)
					_engine.getHolder().unlockCanvasAndPost(_canvas);
			}
		}
	}
	
	/**
	 * Pause game
	 */
	public void pause(){
		synchronized (_engine.getHolder()) {
			set_state(STATE_PAUSE);
		}
	}
	
	public void doStart(){
		synchronized (_engine.getHolder()) {
			set_state(STATE_PLAY);
			if(!this.isAlive())
				this.start();
		}
	}
	
	/**
	 * Safe stop of game finish by user
	 */
	public void safeStop(){
		interrupt();
	}

	// geters and seters
	public boolean is_run() {
		return _run;
	}

	public void set_run(boolean run) {
		_run = run;
	}

	public GameLife get_engine() {
		return _engine;
	}

	public void set_engine(GameLife engine) {
		_engine = engine;
	}

	public int get_state() {
		return _state;
	}

	public void set_state(int state) {
		_state = state;
	}
	
}
